package com.gem.growingtree.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.gem.growingtree.dao.CampusInformationDao;
import com.gem.growingtree.db.DBLink;
import com.gem.growingtree.model.CampusInformation;

public class CampusInformationService implements CampusInformationDao {
	private Connection conn;
	private PreparedStatement pstmt;
	private ResultSet rs;

	@Override
	public boolean Campus(CampusInformation campusInformation) throws Exception {
		boolean flag = false;
		conn = DBLink.getConnection();
		String sql = "insert into campusinformation(campusInformationId,userId,campusInformationTitle,campusInformationContent,campusInformationDate) values(default,?,?,?,?)";
		pstmt = conn.prepareStatement(sql);
		pstmt.setInt(1,campusInformation.getUserId());
		pstmt.setString(2, campusInformation.getCampusInformationTitle());
		pstmt.setString(3, campusInformation.getCampusInformationContent());
		pstmt.setString(4, campusInformation.getCampusInformationDate());
		int rows = pstmt.executeUpdate();
		if (rows == 1) {
			flag = true;
		}
		close();
		return flag;
	}
	public List<CampusInformation> campus2() throws Exception{
		conn= DBLink.getConnection();
		String sql ="select campusInformationTitle,campusInformationContent,campusInformationDate from campusInformation order by campusInformationId desc limit 0,5";
		pstmt=conn.prepareStatement(sql);
		rs=pstmt.executeQuery();
		List<CampusInformation> list= new ArrayList<CampusInformation>();
		while(rs.next()){
			CampusInformation campusInformation1 = new CampusInformation();
			campusInformation1.setCampusInformationTitle(rs.getString(1));
			campusInformation1.setCampusInformationContent(rs.getString(2));
			campusInformation1.setCampusInformationDate(rs.getString(3));
			list.add(campusInformation1);
		}
		close();
		return list;

	}
	public void close() {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
